package com.wlf.server.web.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wlf.server.common.context.BeanContext;
import lombok.SneakyThrows;

import java.util.List;

/**
 * 不想用fastJSON的无奈之举，统一使用Jackson吧。
 * 只适用于Spring环境中，因为要从上下文环境中获取ObjectMapper,
 * 问：为什么要从上下文取，
 * 答：从上下文中取，能保证用的是一个对象，主要是共享配置，而不需要单独配置，保证行为的一致，
 */
public class JSON {
    private static ObjectMapper objectMapper;

    private static ObjectMapper getObjMapper() {
        if (objectMapper != null) {
            return objectMapper;
        } else {
            objectMapper = BeanContext.getBean(ObjectMapper.class);
            return objectMapper;
        }
    }

    /**
     * 很熟悉的API
     */
    @SneakyThrows
    public static <T> T parseObject(String text, Class<T> tClass) {
        return getObjMapper().readValue(text, tClass);
    }

    @SneakyThrows
    public static <T> T parseObject(String text, TypeReference<T> valueTypeRef) {
        return getObjMapper().readValue(text, valueTypeRef);
    }

    @SneakyThrows
    public static String toJSONString(Object o) {
        return getObjMapper().writeValueAsString(o);
    }

    @SneakyThrows
    public static <T> List<T> parseArray(String text, Class<T> tClass) {
        JavaType javaType = getObjMapper().getTypeFactory()
                .constructParametricType(List.class, tClass);
        return getObjMapper().readValue(text, javaType);
    }
}
